package sk.ygor.raynor.client.json.collectiontype;

import sk.ygor.raynor.client.json.JSONSerializer;
import sk.ygor.raynor.client.json.JSONSerializationException;

import java.util.Map;
import java.util.HashMap;

import com.google.gwt.json.client.JSONValue;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONNull;

/**
 * User: ygor
* Date: 2.1.2009
* Time: 19:23:59
*/
public class java_util_Map_JSONSerializer<T> implements JSONSerializer<Map<String, T>> {

    private JSONSerializer<T> itemSerializer;

    public java_util_Map_JSONSerializer(JSONSerializer<T> itemSerializer) {
        this.itemSerializer = itemSerializer;
    }

    public Map<String, T> deserialize(JSONValue jsonValue) {
        if (jsonValue == null || jsonValue.isNull() != null) {
            return null;
        }
        JSONObject jsonObject = jsonValue.isObject();
        if (jsonObject == null) {
            throw new JSONSerializationException("Not a JSONObject. Cannot create Map from: " + jsonValue.toString());
        }
        HashMap<String, T> map = new HashMap<String, T>(); // JSONObject.keySet is a HashMap anyway :( no bother keeping order
        for (String key : jsonObject.keySet()) {
            map.put(key, itemSerializer.deserialize(jsonObject.get(key)));
        }
        return map;
    }

    public JSONValue serialize(Map<String, T> javaObject) {
        if (javaObject == null) {
            return JSONNull.getInstance();
        }
        JSONObject jsonObject = new JSONObject();
        for (Map.Entry<String, T> item : javaObject.entrySet()) {
            jsonObject.put(item.getKey(), itemSerializer.serialize(item.getValue()));
        }
        return jsonObject;
    }
}
